package com.itheima.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.bean.Region;
import com.itheima.mapper.querymapper;
import com.itheima.service.RegionService;
import com.itheima.utils.JedisUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class RegionServiceImpl implements RegionService {

    private InputStream is = null;
    private SqlSession sqlSession = null;
    private List<Region> regions = null;
    String json=null;

    @Override
    public List<Region> findRegionBypid(Integer pid) {

        try {
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);

            sqlSession = build.openSession(true);

            querymapper mapper = sqlSession.getMapper(querymapper.class);

            regions = mapper.QueryCity(pid);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return regions;
    }


    @Override
    public String findRegionFromCacheByPid(Integer pid){
        Jedis  jedis = JedisUtils.getJedis();

        if (jedis.exists("region:"+pid.toString())){
            return jedis.get("region:"+pid.toString());
        }else {
            List<Region> regionBypid = this.findRegionBypid(pid);
            ObjectMapper objectMapper = new ObjectMapper();

            try {
                json = objectMapper.writeValueAsString(regionBypid);
                jedis.set("region:"+pid.toString(),json);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

        }
        return json;
    }
}
